// 秒杀间隔
let intervalTime = 50
chrome.storage.local.get('intervalTime', val => {
  intervalTime = val.intervalTime || 50
})

// 开始时间
let startTime

// 抢购时间
const today = new Date();
let fourPM = new Date().setHours(16, 0, 0, 0); // 设置为下午4点的时间

console.log('看看fourPM', fourPM)
console.log('formatTimestamp(today.getTime())', formatTimestamp(fourPM))
console.log('today', today)
console.log('?', fourPM <= today)

let defaultTime = 0

// 查询是否到了4点
if (fourPM >= today) {
  defaultTime = formatTimestamp(fourPM)
  startTime = fourPM
} else {
  newTime = addMinutes(today, 10)
  console.log('newTime', newTime)
  console.log('formatTimestamp(newTime)', formatTimestamp(newTime))
  defaultTime = formatTimestamp(newTime)
  startTime = newTime
}

chrome.storage.local.get('buyTime', val => {
  console.log('查看现在的buyTime', val.buyTime, formatTimestamp(val.buyTime))
  if (val.buyTime) {
    buyTime = formatTimestamp(val.buyTime)
    startTime = val.buyTime
  } else {
    buyTime = defaultTime
  }
})

// 定时器
let timer = undefined
let settleTimer = undefined
let submitTimer = undefined
// 结算状态
let settleStatus = false
// 提交状态
let submitStatus = false


function formatTimestamp(timestamp) {
  const date = new Date(timestamp);
  const year = date.getFullYear();
  const month = ('0' + (date.getMonth() + 1)).slice(-2);
  const day = ('0' + date.getDate()).slice(-2);
  const hours = ('0' + date.getHours()).slice(-2);
  const minutes = ('0' + date.getMinutes()).slice(-2);
  const seconds = ('0' + date.getSeconds()).slice(-2);
  const milliseconds = ('00' + date.getMilliseconds()).slice(-4);

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${milliseconds}`;
}

// 目前时间十分钟后的整分钟
function addMinutes(time, increaseMinutes) {
  const data = new Date(time)
  let minutes = data.getMinutes() + increaseMinutes;
  let hours = data.getHours();
  if (minutes >= 60) {
    hours += Math.floor(minutes / 60);
    minutes %= 60;
  }
  data.setMinutes(minutes)
  data.setHours(hours)
  data.setSeconds(0)
  data.setMilliseconds(0)
  const newTimestamp = data.getTime()
  return newTimestamp
}

function dateFormat(fmt, date) {
  let ret;
  const opt = {
    "Y+": date.getFullYear().toString(),        // 年
    "m+": (date.getMonth() + 1).toString(),     // 月
    "d+": date.getDate().toString(),            // 日
    "H+": date.getHours().toString(),           // 时
    "M+": date.getMinutes().toString(),         // 分
    "S+": date.getSeconds().toString(),         // 秒
    "SSS": date.getMilliseconds().toString().padStart(3, '0')      // 毫秒
    // 有其他格式化字符需求可以继续添加，必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : ((k === 'SSS' && ret[1].length > 3) ? (opt[k].padStart(ret[1].length, '0')) : (opt[k].padStart(ret[1].length, '0'))));
    }
  }
  return fmt;
}
/**
 * 结算
 */
let settleFun = () => {
  settleStatus = true

  settleTimer = setInterval(() => {
    let go_button = document.getElementById('J_Go')
    if (go_button && go_button.className.indexOf('submit-btn-disabled') === -1) {
      console.log(`当前时间为：${formatTimestamp(new Date())} 开始抢购`)
      clearInterval(settleTimer)
      console.log('点击结算按钮', new Date())
      go_button.click()
      
    } else {
      console.log(`当前时间为：${formatTimestamp(new Date())} 购物车中未选择商品 无法抢购`)
    }
  }, 10)
}

/**
 * 提交
 */
let submitFun = () => {
  clearInterval(timer)
  clearInterval(settleTimer)
  submitStatus = true
  let submitTimer = setInterval(() => {
    let submit_button = document.querySelector(".go-btn")
    if (submit_button) {
      console.log(`当前时间为：${formatTimestamp(new Date())} 开始结算`)
      submit_button.click()
    } else {
      console.log(`当前时间为：${formatTimestamp(new Date())} 很遗憾没抢到`)
    }
    clearInterval(submitTimer)
    chrome.storage.local.clear()
  }, 10)
}

/**
 * 主入口
 */
let main = () => {
  // let startTime = new Date(buyTime).getTime()
  let nowTime = new Date().getTime();
  if (nowTime >= startTime) {
    console.log('时间到了', settleStatus, submitStatus)
    let href = window.location.href
    // 判断当前所在页面
    if (href.indexOf('cart') !== -1) {
      console.log('当前在购物车')
      
      // 购物车
      if (settleStatus === false) {
        console.log(`当前时间为：${formatTimestamp(new Date())} 准备抢购`)
        settleFun()
      }
    } else if (href.indexOf('buy') !== -1) {
      // 结算
      if (submitStatus === false) {
        console.log(`当前时间为：${formatTimestamp(new Date())} 准备结算`)
        submitFun()
      }
    }
  } else {
    console.log(`当前时间为：${formatTimestamp(new Date())} 抢购时间为：${formatTimestamp(buyTime)} 还没到时间`)
  }
}

// 全选
function checkPage() {
  let href = window.location.href
  setTimeout(function() {
    if (href.indexOf('cart') !== -1) {
      let checkButton = document.querySelector("#J_SelectAll1") 
      const hasSelectedClass = checkButton.classList.contains('selected');
      if (hasSelectedClass) {
        return
      } else {
        checkButton.click()
      }
    }
  }, 3000);
 
}

// 捡漏模式
function bargain() {
  let href = window.location.href
  if (href.indexOf('cart') !== -1) {
    let checkButton = document.querySelector("#J_SelectAll1") 
    const hasSelectedClass = checkButton.classList.contains('selected');
    if (hasSelectedClass) {
      location.reload();
    } else {
      checkButton.click()
    }
  }
}

/**
 * 运行
 */
let run = () => {
  settleStatus = false
  submitStatus = false
  console.log('开始运行')
  checkPage()
  timer = setInterval(() => {
    main()
  }, intervalTime)
}

$('body').append(
  `<div id="helper-setting-button">
    <div>抢购设置</div>
  </div>`
)

$('#helper-setting-button').click(() => {
  $('body').append(
    `<div id="helper-setting">
      <div class="helper-setting-form">
        <div class="helper-setting-form-title">抢购设置</div>
        <div class="helper-setting-form-item">
          <label>秒杀间隔：</label>
          <input id="helper-setting-interval" class="helper-setting-form-item-interval" value="${intervalTime}"/>
          <label>（单位：毫秒）</label>
        </div>
        <div class="helper-setting-form-item">
          <label>抢购时间：</label>
          <input id="helper-setting-time" type="text" placeholder="例如：2023-03-24 16:00:00.000" value="${buyTime}" />
        </div>
        <div class="helper-setting-form-item helper-setting-form-bottom">
          <div id="helper-setting-save-button" class="helper-setting-form-item-button">开始抢购</div>
          <div id="helper-setting-stop-button" class="helper-setting-form-item-button">停止</div>
          <div id="helper-setting-cancel-button" class="helper-setting-form-item-button">取消</div>
        </div>
      </div>
    </div>`
  )

  // <input id="helper-setting-time" type="datetime-local" value="${buyTime}"/>

  // 保存按钮
  $('#helper-setting-save-button').click(() => {
    clearInterval(timer)
    clearInterval(settleTimer)
    clearInterval(submitTimer)
    intervalTime = $('#helper-setting-interval').val()
    chrome.storage.local.set({ 'intervalTime': intervalTime })

    buyTime = $('#helper-setting-time').val()
    newTime = parseTimestamp($('#helper-setting-time').val())
    startTime = newTime

    console.log('看看新的时间', newTime)

    chrome.storage.local.set({'buyTime': newTime })
    $('#helper-setting').remove()
    run()
  })

  function parseTimestamp(formattedTime) {
    const date = new Date(formattedTime);
    const timestamp = date.getTime(); // 获取时间戳（单位为毫秒）
    
    return timestamp;
  }

  // 停止按钮
  $('#helper-setting-stop-button').click(() => {
    clearInterval(timer)
    clearInterval(settleTimer)
    clearInterval(submitTimer)
    console.log('项目已停止')
  })

  // 取消按钮
  $('#helper-setting-cancel-button').click(() => {
    $('#helper-setting').remove()
  })
})

run()
